package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi  userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate faceTemplate;

    /**
     * 根据用户id查询用户详细信息(业务层)
     * @param userId
     * @return
     */
    public UserInfoVo selectByid(Long userId) {
        UserInfo userInfo = userInfoApi.selectUserInfo(userId);
        UserInfoVo userInfoVo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, userInfoVo);//属性拷贝，拷贝同名同类型的属性
       if(userInfo.getAge() != null){
           userInfoVo.setAge(userInfo.getAge().toString());
       }
        return userInfoVo;
    }

    //修改信息
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //更换用户头像
    public void updateHeaderPhoto(MultipartFile headPhoto, Long userId) throws IOException {
        //1.把用户头像上传到阿里云oss,得到图片访问路径
        String headPhotoUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度人脸识别检测图片是否有人脸
        boolean checkFace = faceTemplate.checkFace(headPhotoUrl);
        if(!checkFace){
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //3.更新图片的访问路径
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAvatar(headPhotoUrl);
            userInfoApi.update(userInfo);
        }

    }
}
